﻿<div class="d-flex flex-column align-center">
    <MCard Title="Rule configuration" Outlined Width="360" Class="mb-2">
        <MCardText>
            <MSlider @bind-Value="Max"
                     Label="Max characters">
            </MSlider>

            <MCheckbox @bind-Value="_allowSpaces"
                       Label="Allow spaces">
            </MCheckbox>

            <MTextField @bind-Value="Match"
                        Label="Value must match">
            </MTextField>
        </MCardText>
        <MCardActions>
        </MCardActions>
    </MCard>
    <MCard Title="Form" Outlined Width="360">
        <MCardText>
            <MForm @ref="_form">
                <MTextField @bind-Value="Model"
                            Filled
                            Rules="_modelRules"
                            Counter="Convert.ToInt32(_max)"
                            Label="First name">
                </MTextField>
            </MForm>
        </MCardText>
    </MCard>
</div>

@code {
    private MForm? _form;
    private string _model = "Foobar";
    private string _match = "Foobar";
    private bool _allowSpaces;
    private double _max = 6;
    private List<Func<string?, StringBoolean>> _modelRules = new();

    private string Match
    {
        get => _match;
        set
        {
            _match = value;
            _form?.Validate();
        }
    }

    private double Max
    {
        get => _max;
        set
        {
            _max = value;
            _form?.Validate();
        }
    }

    private string Model
    {
        get => _model;
        set
        {
            _model = value;
            _form?.Validate();
        }
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        var rules = new List<Func<string?, StringBoolean>>();
        rules.Add(v => v?.Length <= Max ? true : $"A maximum of {Max} characters is allowed");
        rules.Add(v => v?.IndexOf(' ') < 0 ? true : "No spaces are allowed");
        rules.Add(v => !string.IsNullOrEmpty(v) && v == Match ? true : "Values do not match");

        _modelRules = rules; // have to assign a new instance!
    }

}